 /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package stattracker;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;

/**
 *
 * @author mattcrain
 */
@SuppressWarnings("serial") //shouldn't be serialized
public class StatTracker extends JFrame 
{
	private BaseSystem sys;
    private Dimension dims;
    public StatTracker(BaseSystem sys)
    {
        super("Jabronie's Stat Tracker");
        this.sys = sys;
        addWindowListener(new WindowAdapter() {   // anonymous inner class
            public void windowClosing(WindowEvent e) {
                exit();
            }
        });
        setJMenuBar(new MenuBar(this));
        dims = new Dimension(700, 500);
        setSize(dims);
        this.setPreferredSize(dims);
    
        setLocation((int)Toolkit.getDefaultToolkit().getScreenSize().getWidth()/2-getSize().width/2, //Centers Width
				(int)Toolkit.getDefaultToolkit().getScreenSize().getHeight()/2-getSize().height/2); //Centers Height
        
        splashScreen();

        setVisible(true);
        sys.loadUserProps();
    }
    
    /**
     * Image Size: 
     * 	Width: 685 px
     * 	Height: 445 px
     */
    public void splashScreen()
    {
    	JPanel contentPane = new JPanel();
    	contentPane.setLayout(new BorderLayout());
    	ImageIcon icon = MyUtils.createImageIcon("MedalIcons/SplashScreen.png","");
        JLabel label = new JLabel(icon);
        contentPane.add(label, BorderLayout.CENTER);
        setContentPane(contentPane);
        pack();
        updateTitle("Jabronie Man's Stat Tracker");
    }
    
    public void selectionMenu()
    {
    	final StatTracker parent = this;
    	sys.sortGamers();
    	String defaultGT = sys.getDefaultGT();
    	int selection = 0; //This will keep track of default selection
    	DefaultListModel listModel = new DefaultListModel();
    	for(Gamertag g : sys.getGamers()){
    		if(!MyUtils.emptyString(defaultGT)){
    			if(g.getGamertag().equals(defaultGT)){
    				selection = listModel.getSize();
    			}
    		}
    		listModel.addElement(g.getGamertag());
    	}
    	final JList list = new JList(listModel);
    	final JPanel avatarHolder = new JPanel();
    	avatarHolder.setLayout(new BorderLayout());
    	final JPanel avatar = new JPanel();
    	avatar.setLayout(new BoxLayout(avatar, BoxLayout.PAGE_AXIS));
    	list.setAutoscrolls(true);
    	list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    	
    	list.addListSelectionListener(new ListSelectionListener()
    	{
    		public void valueChanged(ListSelectionEvent e)
    		{
    			String name = (String)(list.getSelectedValue());
    			avatar.removeAll();
    			avatarHolder.removeAll();
    			
    			JLabel newAvatar = new JLabel(sys.lookup(name).getAvatar().getIcon());
    			newAvatar.setVerticalTextPosition(JLabel.BOTTOM);
    			newAvatar.setHorizontalTextPosition(JLabel.CENTER);
    			newAvatar.setAlignmentX(Component.CENTER_ALIGNMENT);
				avatar.add(newAvatar);
    			
    			String date = "";
    			String size = "";
    			File data = sys.getHalo3DataFile(name);
    			if(data.exists())
    			{
    				Date modified = new Date(data.lastModified());
    				date += String.format("Last Update: %s", modified.toString());
    				size += String.format("File Size: %.3f Megabytes", (data.length() / MyUtils.BYTES_TO_MB));
    				JLabel mod = new JLabel(date, SwingConstants.CENTER);
    				JLabel space = new JLabel(size, SwingConstants.CENTER);
    				mod.setHorizontalTextPosition(JLabel.CENTER);
    				space.setHorizontalTextPosition(JLabel.CENTER);
    				mod.setAlignmentX(Component.CENTER_ALIGNMENT);
    				space.setAlignmentX(Component.CENTER_ALIGNMENT);
    				avatar.add(mod);
    				avatar.add(space);
    			}
    			avatarHolder.add(avatar, BorderLayout.LINE_END);
    			
				pack();
				repaint();
    		}
    	});
    	
    	list.addMouseListener(new MouseAdapter() {
    		public void mouseClicked(MouseEvent me) 
    		{
    			list.setSelectedIndex(list.locationToIndex(me.getPoint()));
				if (list.getFirstVisibleIndex() == -1)
					return; // no item selected, maybe list is empty
				String name = (String)(list.getSelectedValue()); 
				if (name == null)
					return;
  
    			if(SwingUtilities.isRightMouseButton(me))
    			{
    				int n = JOptionPane.showConfirmDialog(parent,
    						"Are you sure you want " + name + " as the new default gamertag?",
    						"New Default Gamertag?",
    						JOptionPane.YES_NO_OPTION);
    				if(n == JOptionPane.YES_OPTION){
    					newDefaultGT(name);
    				}
    			}
    			if(me.getClickCount() == 2)
    			{
    				selectGamertag(name);
    			}
    		}
    	});
    	
    	JButton selectButton = new JButton("Select Gamertag");
    	selectButton.addActionListener(new ActionListener()
    	{
    		public void actionPerformed(ActionEvent e)
    		{
    			if(list.getSelectedIndex() == -1)
    				new ErrorMessage("Please Highlight a Gamertag to Select.");
    			else
    			{
    				String name = (String)(list.getSelectedValue());
    				selectGamertag(name);
    			}
    		}
    	});
    	
    	JButton removeButton = new JButton("Remove Gamertag");
    	removeButton.addActionListener(new ActionListener()
    	{
    		public void actionPerformed(ActionEvent e)
    		{
    			if(list.getSelectedIndex() == -1)
    				new ErrorMessage("Please Highlight a Gamertag to Remove");
    			else
    			{
    				String name = (String)(list.getSelectedValue());
    				removeGamertag(name);
    				selectionMenu();
    				save();
    			}
    		}
    	});
    	
    	list.setSelectedIndex(selection);
    	JScrollPane listScroller = MyUtils.makeScroll(list);
    	
    	listScroller.setPreferredSize(new Dimension(250, 400));
		listScroller.setAlignmentX(Component.LEFT_ALIGNMENT);

		JPanel listPane = new JPanel();
		listPane.setLayout(new BoxLayout(listPane, BoxLayout.Y_AXIS));
		JLabel label = new JLabel("Current Gamertags:");
		listPane.add(label);
		listPane.add(Box.createRigidArea(new Dimension(0, 5)));
		listPane.add(listScroller);
		listPane.add(Box.createRigidArea(new Dimension(0, 5)));
		listPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
		
		JPanel buttonPane = new JPanel();
		buttonPane.add(selectButton);
		buttonPane.add(Box.createRigidArea(new Dimension(10, 0)));
		buttonPane.add(removeButton);
		buttonPane.add(Box.createRigidArea(new Dimension(10, 0)));
		
		JPanel contentPane = new JPanel();
        contentPane.setPreferredSize(dims);
        contentPane.setLayout(new BorderLayout());
		contentPane.add(listPane, BorderLayout.LINE_START);
		contentPane.add(Box.createRigidArea(new Dimension(100, 30)), BorderLayout.LINE_END);
		contentPane.add(avatarHolder, BorderLayout.CENTER);
		contentPane.add(buttonPane, BorderLayout.PAGE_END);
		setContentPane(contentPane);
		
		if(!MyUtils.emptyString(defaultGT)){
			selectGamertag(defaultGT);
		}

        pack();
		repaint();
    }
    
    public void selectHalo3Team()
    {
    	sys.sortTeams();
    	
    	DefaultListModel listModel = new DefaultListModel();
    	for(String s : sys.getTeams())
    		listModel.addElement(s);
    	final JList list = new JList(listModel);
    	final JPanel avatars = new JPanel();
    	list.setAutoscrolls(true);
    	list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    	
    	list.addListSelectionListener(new ListSelectionListener()
    	{
    		public void valueChanged(ListSelectionEvent e)
    		{
    			String name = (String)(list.getSelectedValue());
    			avatars.removeAll();
    			avatars.setLayout(new GridLayout(1, sys.getTeammates(name).size()));
    			for(String s : sys.getTeammates(name))
    			{
    				JLabel avatar = new JLabel(s, sys.lookup(s).getAvatar().getIcon(), JLabel.CENTER);
    				avatar.setVerticalTextPosition(JLabel.BOTTOM);
    				avatar.setHorizontalTextPosition(JLabel.CENTER);
    				avatars.add(avatar);
    			}
		
				pack();
				repaint();
    		}
    	});
    	
    	JButton selectButton = new JButton("Display Team Data");
    	selectButton.addActionListener(new ActionListener()
    	{
    		public void actionPerformed(ActionEvent e)
    		{
    			if(list.getSelectedIndex() == -1)
    				new ErrorMessage("Please Highlight a Team to Display Data for.");
    			else
    			{
    				String name = (String)(list.getSelectedValue());
    				sys.displayHalo3Team(name);
    			}
    		}
    	});
    	
    	JButton updateButton = new JButton("Update Team Data");
    	updateButton.addActionListener(new ActionListener()
    	{
    		public void actionPerformed(ActionEvent e)
    		{
    			final String name = (String)(list.getSelectedValue());
    			SwingWorker<Integer, Void> worker = new SwingWorker<Integer, Void>(){
    				public Integer doInBackground()
    				{
    					sys.updateHalo3Team(name);
    					return 0;
    				}
    			};
    			worker.execute();
    		}
    	});
    	
    	JButton removeButton = new JButton("Remove Team");
    	removeButton.addActionListener(new ActionListener()
    	{
    		public void actionPerformed(ActionEvent e)
    		{
    			if(list.getSelectedIndex() == -1)
    				new ErrorMessage("Please Highlight a Team to Remove");
    			else
    			{
    				String name = (String)(list.getSelectedValue());
    				removeTeam(name);
    				selectHalo3Team();
    				save();
    			}
    		}
    	});
    	
    	JScrollPane listScroller = MyUtils.makeScroll(list);
    	listScroller.setPreferredSize(new Dimension(250, 400));
		listScroller.setAlignmentX(Component.LEFT_ALIGNMENT);
		
		JPanel listPane = new JPanel();
		listPane.setLayout(new BoxLayout(listPane, BoxLayout.Y_AXIS));
		JLabel label = new JLabel("Current Teams:");
		listPane.add(label);
		listPane.add(Box.createRigidArea(new Dimension(0, 5)));
		listPane.add(listScroller);
		listPane.add(Box.createRigidArea(new Dimension(0, 5)));
		listPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
		
		JPanel buttonPane = new JPanel();
		buttonPane.add(selectButton);
		buttonPane.add(Box.createRigidArea(new Dimension(10, 0)));
		buttonPane.add(updateButton);
		buttonPane.add(Box.createRigidArea(new Dimension(10, 0)));
		buttonPane.add(removeButton);
		buttonPane.add(Box.createRigidArea(new Dimension(10, 0)));
		
		JPanel contentPane = new JPanel();
        contentPane.setPreferredSize(dims);
        contentPane.setLayout(new BorderLayout());
		contentPane.add(listPane, BorderLayout.LINE_START);
		contentPane.add(avatars, BorderLayout.CENTER);
		contentPane.add(buttonPane, BorderLayout.PAGE_END);
		setContentPane(contentPane);
    
    	pack();
    	repaint();
    }
    
    public void createHalo3Team()
    {
    	updateTitle("Create a team with 2 - 4 members.");
    	sys.sortGamers();
    	DefaultListModel listModel = new DefaultListModel();
    	for(Gamertag g : sys.getGamers())
    		listModel.addElement(g.getGamertag());
    	final JList list = new JList(listModel);
    	list.setAutoscrolls(true);
    	list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    	
    	DefaultListModel listModel2 = new DefaultListModel();
    	final JList team = new JList(listModel2);
    	team.setAutoscrolls(true);
    	team.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    	
    	
    	list.addListSelectionListener(new ListSelectionListener()
    	{
    		public void valueChanged(ListSelectionEvent e)
    		{
				pack();
				repaint();
    		}
    	});
    	
    	JButton addButton = new JButton(">>");
    	addButton.addActionListener(new ActionListener()
    	{
    		public void actionPerformed(ActionEvent e)
    		{
    			if(list.getSelectedIndex() == -1)
    				new ErrorMessage("Please Highlight a Gamertag to Add to the Team.");
    			else
    			{
    				if(((DefaultListModel)team.getModel()).size() >= 4)
    					new ErrorMessage("Teams can NOT have more than four people.");
    				else
    				{
	    				String name = (String)(list.getSelectedValue());
	    				DefaultListModel newListModel = (DefaultListModel)list.getModel();
	    				newListModel.remove(list.getSelectedIndex());
	    				list.setModel(newListModel);
	    				DefaultListModel newModel = (DefaultListModel)team.getModel();
	    				newModel.addElement(name);
	    				team.setModel(newModel);
	    				repaint();
    				}
    				//selectGamertag(name);
    			}
    		}
    	});
    	
    	JButton removeButton = new JButton("<<");
    	removeButton.addActionListener(new ActionListener()
    	{
    		public void actionPerformed(ActionEvent e)
    		{
    			if(team.getSelectedIndex() == -1)
    				new ErrorMessage("Please Highlight a Gamertag to Remove from the Team");
    			else
    			{
    				String name = (String)(team.getSelectedValue());
    				DefaultListModel newTeamModel = (DefaultListModel)team.getModel();
    				newTeamModel.remove(team.getSelectedIndex());
    				team.setModel(newTeamModel);
    				
    				DefaultListModel newModel = (DefaultListModel)list.getModel();
    				Object[] copy = new Object[newModel.size()];
    				newModel.copyInto(copy);
    				ArrayList<String> newNames= new ArrayList<String>(copy.length);
    				for(int i = 0; i < copy.length; i++)
    					newNames.add((String)copy[i]);
    				newNames.add(name);
    				Collections.sort(newNames, new BasicNameComparator());
    				newModel.clear();
    				for(String s : newNames)
    					newModel.addElement(s);
    				list.setModel(newModel);
    				
    				repaint();
    			}
    		}
    		
    		class BasicNameComparator implements Comparator<String>
    		{
    			public int compare(String one, String two)
    			{
    				return one.toLowerCase().compareTo(two.toLowerCase());
    			}
    		}
    	});
    	
    	JButton createButton = new JButton("Create Team");
    	createButton.addActionListener(new ActionListener(){
    		public void actionPerformed(ActionEvent e)
    		{
    			DefaultListModel getTeam = (DefaultListModel)team.getModel();
    			if(getTeam.size() <= 1)
	    			new ErrorMessage("You must select between two and four people to make a team.");
    			else
    			{
    				final String teamName = (String)JOptionPane.showInputDialog(getThis(), 
    						"Please enter in the name you want for this team.",
    						"Team Name", 
    						JOptionPane.INFORMATION_MESSAGE);
    				if(teamName != null)
    				{
    					if(!sys.teamNameTaken(teamName))
    					{
			    			Object[] names = new Object[getTeam.size()];
			    			getTeam.copyInto(names);
			    			final ArrayList<String> teamMembers = new ArrayList<String>(names.length);
			    			for(int i = 0; i < names.length; i++)
			    				teamMembers.add((String)names[i]);
			    			SwingWorker<Integer, Void> worker = new SwingWorker<Integer, Void>(){
			    				public Integer doInBackground()
			    				{
			    					updateTitle("Creating Team and Compiling Data");
			    					sys.createHalo3Team(teamName, teamMembers);
			    					save();
			    					updateTitle("Team: " + teamName + " Created and Saved!");
			    					return 0;
			    				}
			    			};
			    			worker.execute();
    					}
    					else
    						new ErrorMessage("Team Name: '" + teamName + "' is already being used by another team.");
    				}
    			}
    		}
    	});
    	
    	JScrollPane listScroller = MyUtils.makeScroll(list);
    	listScroller.setPreferredSize(new Dimension(250, 400));
		listScroller.setAlignmentX(Component.LEFT_ALIGNMENT);
		
		JScrollPane teamScroller = MyUtils.makeScroll(team);
		teamScroller.setPreferredSize(new Dimension(250, 400));
		listScroller.setAlignmentX(Component.LEFT_ALIGNMENT);
		

		JPanel listPane = new JPanel();
		listPane.setLayout(new BoxLayout(listPane, BoxLayout.Y_AXIS));
		JLabel label = new JLabel("Current Gamertags:");
		listPane.add(label);
		listPane.add(Box.createRigidArea(new Dimension(0, 5)));
		listPane.add(listScroller);
		listPane.add(Box.createRigidArea(new Dimension(0, 5)));
		listPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
		
		JPanel teamPane = new JPanel();
		teamPane.setLayout(new BoxLayout(teamPane, BoxLayout.Y_AXIS));
		label = new JLabel("Current Team Members:");
		teamPane.add(label);
		teamPane.add(Box.createRigidArea(new Dimension(0, 5)));
		teamPane.add(teamScroller);
		teamPane.add(Box.createRigidArea(new Dimension(0, 5)));
		teamPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
		
		JPanel buttonPane = new JPanel();
		buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.PAGE_AXIS));
		buttonPane.add(Box.createRigidArea(new Dimension(40, 175)));
		buttonPane.add(addButton);
		buttonPane.add(Box.createRigidArea(new Dimension(0, 20)));
		buttonPane.add(removeButton);
		buttonPane.add(Box.createRigidArea(new Dimension(0, 20)));
		
		JPanel createPane = new JPanel();
		createPane.add(createButton);
    	
		JPanel contentPane = new JPanel();
        contentPane.setPreferredSize(dims);
        contentPane.setLayout(new BorderLayout());
		contentPane.add(listPane, BorderLayout.LINE_START);
		contentPane.add(buttonPane, BorderLayout.CENTER);
		contentPane.add(teamPane, BorderLayout.LINE_END);
		contentPane.add(createPane, BorderLayout.PAGE_END);
		setContentPane(contentPane);

        pack();
		repaint();
    }
    
    private StatTracker getThis()
    {
    	return this;
    }
    
    public void addGamerMenu()
    {
        JPanel content = new JPanel();
        content.setPreferredSize(dims);
        final JTextField field = new JTextField(40);
        JButton add = new JButton("Add Gamertag");
        JButton clear = new JButton("Clear Text");
        JButton done = new JButton("Finished");
        
        add.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                String gamer = field.getText();
                if(gamer.length() > 0)
                {
                    addGamertag(gamer.trim());
                    save();
                }
                else
                    noGTEnteredMessage();
                field.setText("");
            }
        });
        
        clear.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                field.setText("");
            }
        });
        
        done.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
               selectionMenu(); 
            }
        }); 
        
        JPanel buttons = new JPanel();
        buttons.add(add);
        buttons.add(clear);
        buttons.add(done);
        JLabel enter = new JLabel("Enter Gamertag: ");
        JPanel textBox = new JPanel();
        textBox.add(enter);
        textBox.add(field);
        JPanel test = new JPanel();
        test.setLayout(new BoxLayout(test, BoxLayout.PAGE_AXIS));
        test.add(textBox);
        test.add(buttons);
        content.add(test);
        setContentPane(content);
        pack();
        repaint();
    }
    
    
    public void displayHalo3Data()
    {
    	if(sys.hasGamerSelected())
    	{
	    	updateTitle("Building Halo 3 Window for " + sys.getSelectedName());
	    	SwingWorker<Integer, Void> worker = new SwingWorker<Integer, Void>()
	    	{
	    		public Integer doInBackground()
	    		{
	    			sys.displaySelectedHalo3Data();
	    			updateTitle();
	    			return 1;
	    		}
	    	};
	    	worker.execute();
    	}
    	else
    	{
    		new ErrorMessage("Must select a gamer before you can view any data.");
    	}
    }
    
    public void getGameData(boolean gameUpdate, Game game)
    {
    	final boolean updateGames = gameUpdate;
    	if(sys.hasGamerSelected())
    	{
	    	int n = JOptionPane.showConfirmDialog(this,
					"Are you sure you want get the game data for " + sys.getSelectedName() + "? It takes around 3 mins / 1000 games played." +
					"\nIt's also dependent on your internet connection and Bungie's servers.",
					"Get Data for " + sys.getSelectedName() + "?",
					JOptionPane.YES_NO_OPTION);
	    	if(n == JOptionPane.YES_OPTION)
	    	{
	    		sys.setParent(this);
	    		final Game gameType = game;
	    		SwingWorker<Integer, Void> worker = new SwingWorker<Integer, Void>()
	            {
	    			public Integer doInBackground()
	    			{
	    				long startTime = System.currentTimeMillis();
	    				switch (gameType)
	    				{
	    					case HALO3:
	    						sys.getSelectedHalo3Data(updateGames);
	    						break;
	    					case REACH_BETA:
	    						sys.getSelectedHaloReachBetaData(updateGames);
	    						break;
	    					default:
	    						new ErrorMessage("Game doesn't match any recognized type.");
	    				}
	    				displayTime(System.currentTimeMillis() - startTime);
	    				return 1;
	    			}
	            };
	            worker.execute();
	    	}
    	}
    	else
    	{
    		new ErrorMessage("No Gamer Selected to get Data.");
    	}
    }
    
    private void displayTime(long millis)
	{
		JOptionPane.showMessageDialog(this,
				"Finished Update.\n" +
				"Took: " + MyUtils.formatTime((int)millis/1000),
				"Update Complete",
				JOptionPane.INFORMATION_MESSAGE);
	}
    
    public void setDefaultGT(){
    	 String response = JOptionPane.showInputDialog(null,
    			  "This will clear the old default",
    			  "Enter the default GT. \n Leave blank to cancel.",
    			  JOptionPane.QUESTION_MESSAGE);
    	 newDefaultGT(response);
    }
    
    private void newDefaultGT(String newDefault){
    	if(!MyUtils.emptyString(newDefault)){
    		sys.setDefaultGT(newDefault);
    	}
    }
    
    public void importFriendsList()
    {
    	importInstructions();
    	FileDialog fd = new FileDialog(this, "Open", FileDialog.LOAD);
        fd.setVisible(true);
        if (fd.getFile() == null)
            return;
        final String file = fd.getDirectory() + fd.getFile();
        SwingWorker<Integer, Void> worker = new SwingWorker<Integer, Void>()
        {
			public Integer doInBackground()
			{
				updateTitle("Currently Importing Friends. This may take a minute.");
				sys.addWorker();
				new FriendsListParser(sys, file);
				sys.workerDone();
				sys.waitOnWork();
				updateTitle("Friends Successfully Imported!");
				selectionMenu();
				save();
				return 0;
			}
        };
        worker.execute();
    }

	private void importInstructions() 
	{
		JOptionPane.showMessageDialog(this,
		    "A Series of Popups will walk you through the import process.\n" +
		    "Click 'OK' to continue.", "Import Process",
		    JOptionPane.INFORMATION_MESSAGE);
    	JOptionPane.showMessageDialog(this,
    		    "Go to Xbox.com and sign-in using your Windows Live ID.\n" +
    		    "This should be the ID of the Gamertag that has the friends you want.\n" +
    		    "Once you've signed in click 'OK'.", "Import Process",
    		    JOptionPane.INFORMATION_MESSAGE);
    	JOptionPane.showMessageDialog(this,
    		    "In the top right there's a drop down that by default selects 'My Xbox'.\n" +
    		    "Click the menu and select 'View Friends'.\n" +
    		    "This should bring up a list of your friends, when it has click 'OK'", "Import Process",
    		    JOptionPane.INFORMATION_MESSAGE);
    	JOptionPane.showMessageDialog(this,
    		    "Now that you can see all your friends right-click on the side.\n" +
    		    "Make sure you are right-clicking on the background and not any of your friends.\n" +
    		    "There should be an option that says 'View Source' or 'View Page Source'.\n" +
    		    "Click that option and a separate page full of html source code should appear.\n" +
    		    "Click 'OK' when that page appears.", "Import Process",
    		    JOptionPane.INFORMATION_MESSAGE);
    	JOptionPane.showMessageDialog(this,
    		    "Now that you have the source code select all of it.\n" +
    		    "   (Select All: Windows - Ctrl + A; Mac: Command + A)\n" +
    		    "and copy it. (Windows - Ctrl + C; Mac: Command + C)\n" +
    		    "paste it (Ctrl + V or Command + V) into some type of text editor.\n" +
    		    "Save it in a Plain Text format (e.g. .txt)\n" +
    		    "If you are using OS X use TextEdit and save in Rich Text Format\n" +
    		    "Click 'OK' when you have created the file.", "Import Process",
    		    JOptionPane.INFORMATION_MESSAGE);
    	JOptionPane.showMessageDialog(this,
    		    "The next dialog will ask you to local the file you just saved.\n" +
    		    "It the program will then import all of your friends.", "Import Process",
    		    JOptionPane.INFORMATION_MESSAGE);
	}
	
	public void clearDefaultGT()
	{
		sys.clearDefaultGT();
		updateTitle("Cleared Defualt Gamertag.");
	}
	
	public void clearDefaultList()
	{
		sys.clearDefaultList();
		updateTitle("Default List Cleared.");
	}
	
	public void setAudioLocation()
	{
		JOptionPane.showMessageDialog(this, 
				"Download the audio package from http://www.mattcrain.com\n" +
				"Unzip the files to your desired location, don't separate any of the files\n" +
				"The next dialog will ask you to select one of the audio files,\n" +
				"The program will then know the location of all of them.",
				"How to get the audio.",
				JOptionPane.INFORMATION_MESSAGE);
		FileDialog fd = new FileDialog(this, "Open", FileDialog.LOAD);
        fd.setVisible(true);
        if (fd.getFile() == null)
            return;
        String audioLocation = fd.getDirectory();
        sys.setAudioLocation(audioLocation);
	}
	
	public void clearAudioLocation()
	{
		sys.clearAudioLocation();
		updateTitle("Cleared Audio Location.");
	}
    
    public void about()
	{
		JOptionPane.showMessageDialog(this,
			    "Jabronie Man's Halo 3 Stat Tracker\n" +
			    "Version: Beta 2\n" +
			    "Requirements: Java 6, OS X on a Intel based Mac\n or " +
			    "Windows XP/Vista, CPU - Pentium 4 or higher,\n" +
			    "An Internet connection for Gamertag addition and data retrieval\n" +
			    "Built: 3/25/09\n" +
			    "Created By: Matt Crain\n" +
			    "Website: http://www.mattcrain.com\n" +
			    "Forum: http://www.mattcrain.com/forum\n" +
			    "If you find a bug please post it on the forum, or e-mail me at:" +
			    " mattcrain@gmail.com\n" +
			    "Feel free to distribute this program at will as it is completely free", 
			    "About", JOptionPane.INFORMATION_MESSAGE);
	}

    
    private void addGamertag(String newGamer)
    {
        if(!sys.addGamer(newGamer))
            noHaloRecord(newGamer);
    }
    
    private void noGTEnteredMessage()
    {
        JOptionPane.showMessageDialog(this,
                    "No Gamertag has been entered.",
                    "Nothing Entered",
                    JOptionPane.ERROR_MESSAGE);
    }
    
    private void noHaloRecord(String name)
    {
        JOptionPane.showMessageDialog(this,
			    "Bungie.net has no record of "+name+" playing Halo 3." +
			    		"The Gamertag was not added into the system.\n",
			    "Incorrect Gamertag",
			    JOptionPane.ERROR_MESSAGE);
    }
    
    public boolean downloadH3SaveFromDB()
    {
    	int option = JOptionPane.showConfirmDialog(this, "It appears that the online database has a more recent version of the file." +
							    					"  Would you like to download it?",
							    					"Download from DB?", JOptionPane.YES_NO_OPTION);
    	return option == JOptionPane.YES_OPTION;
    }
    
    public void saveAs()
    {
    	FileDialog fd = new FileDialog(this, "Save", FileDialog.SAVE);
        fd.setVisible(true);
        if (fd.getFile() == null)
            return;
        final String file = fd.getDirectory() + fd.getFile();
        SwingWorker<Integer, Void> worker = new SwingWorker<Integer, Void>(){
			public Integer doInBackground()
			{
		        updateTitle("Saving... Please Wait");
		        sys.saveSystem(file);
		        updateTitle("Save Complete!");
		        return 1;
			}
        };
        worker.execute();
    }
    
    public void save()
    {
    	if(!sys.hasSaveLocation())
	    	saveAs();
    	else
    	{
    		SwingWorker<Integer, Void> worker = new SwingWorker<Integer, Void>(){
    			public Integer doInBackground()
    			{
		    		updateTitle("Saving... Please Wait");
		    		sys.quickSave();
		    		updateTitle("Save Complete!");
		    		return 1;
    			}
    		};
    		worker.execute();
    	}
    }
    
    public void load()
    {
    	FileDialog fd = new FileDialog(this, "Open", FileDialog.LOAD);
        fd.setVisible(true);
        if (fd.getFile() == null)
            return;
        String file = fd.getDirectory() + fd.getFile();
        updateTitle("Loading: " + fd.getFile() + "...");
        sys.loadSystem(file);
        updateTitle("Load Complete!");
        selectionMenu();
    }
    
    private void removeTeam(String teamName)
    {
    	int n = -1;
    	if(sys.hasTeamFile(teamName))
    	{
    		n = JOptionPane.showConfirmDialog(this,
    				"Would you also like to delete the saved data for team: " + teamName,
    				"Delete Team Data for " + teamName + "?",
    				JOptionPane.YES_NO_OPTION);
    	}
    	if(!sys.removeTeam(teamName, n == JOptionPane.YES_OPTION))
    		new ErrorMessage("Error in Removing the Team: " + teamName);
    	else
    		updateTitle(teamName + " Removed!");
    }
    
    private void removeGamertag(String gamertag)
    {
    	int n = -1;
    	if(sys.hasGameFile(gamertag))
    	{
	    	n = JOptionPane.showConfirmDialog(this,
				"Would you also like to delete " + gamertag +"'s Game Data?",
				"Delete Data for " + gamertag + "?",
				JOptionPane.YES_NO_OPTION);
    	}
    	if(!sys.removeGamer(gamertag, n == JOptionPane.YES_OPTION))
    		new ErrorMessage("Error in Removing the Gamertag: " + gamertag);
    	else
    		updateTitle(gamertag + " Removed!");
    }
    
    private void selectGamertag(String gamertag)
    {
    	if(!sys.selectGamer(gamertag))
    		new ErrorMessage("Error Selecting the Gamertag: " + gamertag);
    	else
    		updateTitle(gamertag + " Selected!");
    }
    
    public void updateTitle()
    {
    	if(sys.getSelectedName().equals(""))
    		updateTitle("No Gamertag Currently Selected.");
    	else
    		updateTitle("Current Selected Gamertag: " + sys.getSelectedName());
    }
    
    public void updateTitle(String title)
    {
    	setTitle(title);
    }
    
    public void exit()
    {
    	if(sys.isSaving())
    	{
    		new ErrorMessage("The system is currently saving, exiting would corrupt the save file.\n" +
    						 "Try exiting again when it notifies you that the save is complete.");
    	}
    	else
    		exitSystem();
    }
    
    private void exitSystem()
    {
        System.exit(0);
    }

	public void dbTest() 
	{
		try {
			Database db = Database.getInstance();
			updateTitle(String.format("Uploading %s.halo3 to database...", sys.getSelectedName()));
			db.insertHalo3SaveFile(1, sys.getSelectedName()+".halo3");
			updateTitle("Upload completed successfully!");
		} catch (DatabaseInaccessibleException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
	}
}
class MenuBar extends JMenuBar
{
	private static final long serialVersionUID = 1L;
	private StatTracker pf; // The Parent Frame
    
    public MenuBar(StatTracker parent)
    {
        pf = parent;
        
        JMenu fileMenu, GTMenu, HaloMenu, ReachBetaMenu, TeamMenu, UserMenu, HelpMenu, DevMenu;
        JMenuItem item;
        
        fileMenu = new JMenu("File");
        fileMenu.setMnemonic(KeyEvent.VK_F);
        item = new JMenuItem("Save");
        item.addActionListener(new SystemListener());
        fileMenu.add(item);
        item = new JMenuItem("Save As");
        item.addActionListener(new SystemListener());
        fileMenu.add(item);
        item = new JMenuItem("Open");
        item.addActionListener(new SystemListener());
        fileMenu.add(item);
        fileMenu.add(new JSeparator());
        item = new JMenuItem("Exit");
        item.addActionListener(new SystemListener());
        fileMenu.add(item);
        add(fileMenu);
        
        GTMenu = new JMenu("Gamertag");
        GTMenu.setMnemonic(KeyEvent.VK_G);
        item = new JMenuItem("Add Gamertag(s)");
        item.addActionListener(new SystemListener());
        GTMenu.add(item);
        item = new JMenuItem("Select Gamertag");
        item.addActionListener(new SystemListener());
        GTMenu.add(item);
        GTMenu.add(new JSeparator());
        item = new JMenuItem("Import Friends List");
        item.addActionListener(new SystemListener());
        GTMenu.add(item);
        add(GTMenu);
        
        HaloMenu = new JMenu("Halo 3");
        item = new JMenuItem("Display Player's Halo 3 Data");
        item.addActionListener(new SystemListener());
        HaloMenu.add(item);
        HaloMenu.add(new JSeparator());
        item = new JMenuItem("Get Player's Halo 3 Data");
        item.addActionListener(new SystemListener());
        HaloMenu.add(item);
        item = new JMenuItem("Update Player's Halo 3 Stats");
        item.addActionListener(new SystemListener());
        HaloMenu.add(item);
        add(HaloMenu);
        
        ReachBetaMenu = new JMenu("Reach Beta");
        item = new JMenuItem("Display Player's Halo Reach Beta Data");
        item.addActionListener(new SystemListener());
        ReachBetaMenu.add(item);
        ReachBetaMenu.add(new JSeparator());
        item = new JMenuItem("Get Player's Halo Reach Beta Data");
        item.addActionListener(new SystemListener());
        ReachBetaMenu.add(item);
        item = new JMenuItem("Update Player's Halo Reach Beta Stats");
        item.addActionListener(new SystemListener());
        ReachBetaMenu.add(item);
        add(ReachBetaMenu);
        
        TeamMenu = new JMenu("Teams");
        item = new JMenuItem("Create a Halo 3 Team");
        item.addActionListener(new SystemListener());
        TeamMenu.add(item);
        item = new JMenuItem("Select a Halo 3 Team");
        item.addActionListener(new SystemListener());
        TeamMenu.add(item);
        add(TeamMenu);
        
        UserMenu = new JMenu("User");
        UserMenu.setMnemonic(KeyEvent.VK_U);
        item = new JMenuItem("Clear Default Gamertag");
        item.addActionListener(new SystemListener());
        UserMenu.add(item);
        item = new JMenuItem("Clear Default List");
        item.addActionListener(new SystemListener());
        UserMenu.add(item);
        item = new JMenuItem("Set Audio Location");
        item.addActionListener(new SystemListener());
        UserMenu.add(item);
        item = new JMenuItem("Clear Audio Location");
        item.addActionListener(new SystemListener());
        UserMenu.add(item);
        add(UserMenu);
        
        HelpMenu = new JMenu("Help");
        HelpMenu.setMnemonic(KeyEvent.VK_H);
        item = new JMenuItem("About");
        item.addActionListener(new SystemListener());
        HelpMenu.add(item);
        item = new JMenuItem("Splash Screen");
        item.addActionListener(new SystemListener());
        HelpMenu.add(item);
        add(HelpMenu);
        
        DevMenu = new JMenu("Dev");
        item = new JMenuItem("DB Conn Test");
        item.addActionListener(new SystemListener());
        DevMenu.add(item);
        add(DevMenu);
        
    }
    
    class SystemListener implements ActionListener
    {
    	public void actionPerformed(ActionEvent e)
    	{
            JMenuItem source = (JMenuItem) e.getSource();
            String text = source.getText();
            if(text.equals("Save"))
                pf.save();
            else if(text.equals("Save As"))
            	pf.saveAs();
            else if(text.equals("Open"))
                pf.load();
            else if(text.equals("Exit"))
                pf.exit();
            else if(text.equals("Add Gamertag(s)"))
                pf.addGamerMenu();
            else if(text.equals("Select Gamertag"))
                pf.selectionMenu();
            else if(text.equals("Import Friends List"))
            	pf.importFriendsList();
            else if(text.equals("Display Player's Halo 3 Data"))
            	pf.displayHalo3Data();
            else if(text.equals("Get Player's Halo 3 Data"))
            	pf.getGameData(true, Game.HALO3);
            else if(text.equals("Update Player's Halo 3 Stats"))
            	pf.getGameData(false, Game.HALO3);
            else if(text.equals("Display Player's Halo Reach Beta Data"))
            	pf.displayHalo3Data();
            else if(text.equals("Get Player's Halo Reach Beta Data"))
            	pf.getGameData(true, Game.REACH_BETA);
            else if(text.equals("Update Player's Halo Reach Beta Stats"))
            	pf.getGameData(false, Game.REACH_BETA);
            else if(text.equals("Create a Halo 3 Team"))
            	pf.createHalo3Team();
            else if(text.equals("Select a Halo 3 Team"))
            	pf.selectHalo3Team();
            else if(text.equals("Clear Default Gamertag"))
            	pf.clearDefaultGT();
            else if(text.equals("Clear Default List"))
            	pf.clearDefaultList();
            else if(text.equals("Set Audio Location"))
            	pf.setAudioLocation();
            else if(text.equals("Clear Audio Location"))
            	pf.clearAudioLocation();
            else if(text.equals("About"))
            	pf.about();
            else if(text.equals("Splash Screen"))
            	pf.splashScreen();
            else if(text.equals("DB Conn Test"))
            	pf.dbTest();
            else
                System.out.println("Invalid Command");
    	}
    } 
}
